package com.hua.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hua.pojo.Invite;
import com.hua.pojo.User;
import com.hua.pojo.securityUser.SecurityUser;
import com.hua.result.R;
import com.hua.service.InviteService;
import com.hua.service.UserService;
import com.hua.utils.HuaUtil;
import com.hua.utils.MyStringHandle;
import com.hua.vo.RegisterFrom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ONE-X
 * @date 2020/11/09
 */
@Controller
public class LoginController {
	static Logger logger = LoggerFactory.getLogger("LoginController");

	@Autowired
	UserService userService;

	@Autowired
	InviteService inviteService;

	/**
	 * 首页
	 * @return
	 */
	@GetMapping({"/","/index"})
	public String toindex(){
		return "index";
	}

	/**
	 * 登录页面
	 * @return
	 */
	@GetMapping("/login")
	public String tologin(){
		return "login";
	}

	/**
	 * 跳转到注册页面
	 * @return
	 */
	@GetMapping("/register")
	public String toregister(){
		return "register";
	}


	@PostMapping("/register")
	public String register(RegisterFrom registerFrom, Model model){
		System.out.println(registerFrom);
		// 密码用户名不能包含空格
		if(!(MyStringHandle.StringNotNULLAndAir(registerFrom.getPassword()) && MyStringHandle.StringNotNULLAndAir(registerFrom.getUsername()) && MyStringHandle.StringNotNULLAndAir(registerFrom.getRepassword()) && MyStringHandle.StringNotNULLAndAir(registerFrom.getCode()))){
			model.addAttribute("error","密码用户名不能包含空格");
			return "register";
		}
		// 首先得两次密码一致
		if(!(registerFrom.getPassword().equals(registerFrom.getRepassword()))){
			model.addAttribute("error","两次密码不一致");
			return "register";
		}
		// 判断用户名是否存在
		int flag = userService.count(new QueryWrapper<User>().eq("username", registerFrom.getUsername()));
		if(flag > 0){
			model.addAttribute("error","用户名已存在");
			return "register";
		}

		// 判断验证码是否存在并且有效
		flag = inviteService.count(new QueryWrapper<Invite>().eq("code",registerFrom.getCode()).eq("status","0"));
		if(flag <= 0){
			model.addAttribute("error","验证码无效或者已经被注册");
			return "register";
		}

		// 开始注册
		try{
			userService.registerUser(registerFrom);
		}catch (Exception e){
			logger.error("新增用户时出现了错误 大错误");
			e.printStackTrace();
			model.addAttribute("error","请重新尝试");
			return "register";
		}
		return "redirect:/login";
	}

	// 上传图片
	@ResponseBody
	@PostMapping("/upload")
	public String upload(MultipartFile file, HttpServletRequest request){
		String uid = HuaUtil.returnAuthentication();
		String filePath = "C:\\ONEX\\headImg\\";
		//获取文件名
		String fileName = file.getOriginalFilename();
		//获取文件后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		fileName = uid+suffixName;
		try {
			// 上传成功
			file.transferTo(new File(filePath,fileName));
			// 修改user里面的图片 /images/avatar/avatar-1.jpg
		} catch (IOException e) {
			logger.error("文件添加失败");
			e.printStackTrace();
		}
		return JSON.toJSONString(R.ok());
	}

	// 文件下载
	@GetMapping("/download")
	public String downloads(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String path = "C:\\ONEX\\headImg\\";

		// 设置 response响应头部
		response.reset();	// 设置页面不缓存，清空buffer
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data"); //二进制传输数据
		//设置响应头
		String fileName = "6e8749ce0d2b4b53ad47a428e3030a50.jpg";
		response.setHeader("Content-Disposition",
				"attachment;filename="+fileName);
		File file = new File(path,fileName);
		System.out.println(file.exists());
		InputStream inputStream = new FileInputStream(file);
		int len = 0;
		byte[] bytes = new byte[1024];
		// 写出文件
		ServletOutputStream outputStream = response.getOutputStream();
		while ((len = inputStream.read(bytes)) != -1){
			outputStream.write(bytes,0,len);
			outputStream.flush();
		}
		outputStream.close();
		inputStream.close();
		return null;
	}



	@PostMapping("/uploadText")
	@ResponseBody
	public String uploadPicture(@RequestParam("upload") MultipartFile file, Model model, HttpServletRequest request, HttpSession session, HttpServletResponse response) {

		try {
			String uid = HuaUtil.getUuid();
			String filePath = "C:\\ONEX\\headImg\\text\\";
			String fileName = file.getOriginalFilename();
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			fileName = uid+suffixName;
			file.transferTo(new File(filePath,fileName));
			String url = "\\headImg\\text\\"+ fileName;
			Map<String, String> reMap = new HashMap<String, String>();
			//必须返回这样格式的json字符串
			reMap.put("uploaded", "1");
			reMap.put("url", url);
			return JSON.toJSONString(reMap);
		} catch (Exception e) {
			logger.error("上传图片失败", e);
			return "false";
		}
	}
}
